package com.qf.taobei.service.impl;

import com.qf.taobei.entity.RespBean;
import com.qf.taobei.entity.Store;
import com.qf.taobei.entity.User;
import com.qf.taobei.entity.bo.StoreOrderProduct;
import com.qf.taobei.entity.bo.StoreUser;
import com.qf.taobei.entity.vo.ProductIdAndName;
import com.qf.taobei.entity.vo.ProductVo;
import com.qf.taobei.entity.vo.StoreTotal;
import com.qf.taobei.entity.vo.Vo;
import com.qf.taobei.mapper.ProductMapper;
import com.qf.taobei.mapper.StoreMapper;
import com.qf.taobei.mapper.UserMapper;
import com.qf.taobei.service.StoreService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author:CRT
 * @Date:
 * @Version:
 */
@Service
public class StoreServiceImpl implements StoreService {
    @Autowired
    StoreMapper storeMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ProductMapper productMapper;
    @Override
    public RespBean addStore(Store store, HttpServletRequest request, MultipartFile file) {
        //获取用户id
        User user = (User)request.getSession().getAttribute("user");
        Integer uid = user.getId();
        User newUser = new User();
        newUser.setId(uid);
        newUser.setStatus(1);
        //获取当前时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        //测试使用
        //Integer uid=1;
        store.setRegisterTime(time);
        store.setUid(uid);
        //上传照片
        String path = request.getServletContext().getRealPath("/asserts/img");
        //获取文件名
        String fileName = file.getOriginalFilename();
        //解决重名
        fileName = UUID.randomUUID().toString() +"_"+fileName;
        File file1 = new File(path);
        if (!file1.exists()){
            //创建文件路径
            file1.mkdirs();
        }

        //存储文件
        try {
            file.transferTo(new File(path,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取照片地址
        //请求协议
        String url = request.getScheme()+"://"
                //服务器的域名
                +request.getServerName()+":"
                //端口号
                +request.getServerPort()
                //项目名
                +request.getContextPath()
                //文件路径
                +"/asserts/img/"+fileName;

        store.setImgUrl(url);
        int i = storeMapper.addStore(store);
        if (i!=0){
            userMapper.updateUser(newUser);
            return RespBean.respSuccess("注册店铺成功");
        }
        return RespBean.respError("注册店铺失败");
    }

    @Override
    public RespBean deleteStoresTrue(int[] storeIds) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < storeIds.length; i++) {
            list.add(storeIds[i]);
        }
        int i = storeMapper.deleteStoreByStoreIdsTrue(list);
        if (i!=0){
            return RespBean.respSuccess("真删除店铺成功");
        }
        return RespBean.respError("真删除店铺失败");
    }

    @Override
    public RespBean queryStoreByUId(int uid) {
        Store store = new Store();
        store.setUid(uid);
        List<Store> list = storeMapper.queryStores(store);
        if (list.size()!=0){
            return RespBean.respSuccess("查询店铺成功",list);
        }
        return RespBean.respError("查询店铺失败");
    }

    @Override
    public RespBean queryStoreBySessionId(HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute("user");
        Integer uid = user.getId();
        Store store = new Store();
        store.setUid(uid);
        List<Store> list = storeMapper.queryStores(store);
        if (list.size()!=0){
            return RespBean.respSuccess("查询店铺成功",list);
        }
        return RespBean.respError("查询店铺失败");
    }

    @Override
    public RespBean queryStoreByStoreId(int storeId) {
        Store store = new Store();
        store.setId(storeId);
        List<Store> list = storeMapper.queryStores(store);
        if (list.size()!=0){
            return RespBean.respSuccess("获取店铺信息成功",list.get(0));
        }
        return RespBean.respError("获取店铺信息失败");
    }

    @Override
    public RespBean saveStoreId(int storeId, HttpServletRequest request) {
        if (storeId!=0){
            request.getSession().setAttribute("storeId",storeId);
            return  RespBean.respSuccess("保存店铺id成功");
        }
        return RespBean.respError("保存店铺id失败");


    }

    @Override
    public RespBean updateStoreByStoreId(HttpServletRequest request,Store store,MultipartFile file) {
        //获取店铺id
        int storeId = (Integer) request.getSession().getAttribute("storeId");
        store.setId(storeId);
        //上传照片
        String path = request.getServletContext().getRealPath("/asserts/img");
        //获取文件名
        String fileName = file.getOriginalFilename();
        //解决重名
        fileName = UUID.randomUUID().toString() +"_"+fileName;
        File file1 = new File(path);
        if (!file1.exists()){
            //创建文件路径
            file1.mkdirs();
        }

        //存储文件
        try {
            file.transferTo(new File(path,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取照片地址
        //请求协议
        String url = request.getScheme()+"://"
                //服务器的域名
                +request.getServerName()+":"
                //端口号
                +request.getServerPort()
                //项目名
                +request.getContextPath()
                //文件路径
                +"/asserts/img/"+fileName;

        /*store.setImgUrl(url);*/
        String storeImg = (String)request.getSession().getAttribute("storeImg");
        store.setImgUrl(storeImg);
        int i = storeMapper.updateStoreByStoreId(store);
        if (i!=0){
            return RespBean.respSuccess("修改店铺信息成功");
        }
        return RespBean.respError("修改用户信息失败");
    }

    @Override
    public RespBean tranferStore(User user, String yourName, String yourPassword, HttpServletRequest request) {
        int storeId = (Integer) request.getSession().getAttribute("storeId");
        Store store = storeMapper.queryStoreByStoreId(storeId);
        User user1 = (User) request.getSession().getAttribute("user");
        if (yourName.equals(user1.getUsername()) && yourPassword.equals(user1.getPassword())){
            //判断转让人信息
            List<User> list = userMapper.searchUserList(user);
            if (list.size()!=0){
                User user2 = list.get(0);
                Integer id = user2.getId();
                store.setUid(id);
                int i = storeMapper.updateStoreByStoreId(store);
                if (i!=0){
                    return RespBean.respSuccess("转让成功");
                }else {
                    return RespBean.respError("转让失败（修改用户id失败）");
                }
            }else {
                return RespBean.respError("转让失败（没有找到该用户）");
            }
        }
        return RespBean.respError("转让失败(您的信息不正确)");
    }

    @Override
    public RespBean lougoutStore(String tel, String password,HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (tel.equals(user.getTel()) && password.equals(user.getPassword())){
            Integer storeId = (Integer) request.getSession().getAttribute("storeId");
            ArrayList<Integer> list = new ArrayList<>();
            list.add(storeId);
            int i = storeMapper.deleteStoreByStoreIdsFlase(list);
            if (i!=0){
                int i1 = storeMapper.deleteProductByStoreIdFalse(storeId);
                return RespBean.respSuccess("注销成功,本店的"+i1+"商品也将被下架");
            }
            return RespBean.respError("注销失败");
        }
        return RespBean.respError("注销失败");
    }

    @Override
    public RespBean deleteStoreByStoreIdFalse(int storeId) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(storeId);
        int i = storeMapper.deleteStoreByStoreIdsFlase(list);
        if (i!=0){
            int i1 = storeMapper.deleteProductByStoreIdFalse(storeId);
            return RespBean.respSuccess("伪删除成功，本店的"+i1+"商品也将被下架");
        }
        return RespBean.respError("伪删除失败");
    }

    @Override
    public RespBean deleteStoreByStoreIdsFalse(int[] storeIds) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i <storeIds.length; i++) {
            storeMapper.deleteProductByStoreIdFalse(storeIds[i]);
            list.add(storeIds[i]);
        }
        int i = storeMapper.deleteStoreByStoreIdsFlase(list);
        if (i!=0){
            return RespBean.respSuccess("伪删除成功");
        }
        return RespBean.respError("伪删除失败");
    }

    @Override
    public RespBean quertStoreUser(StoreUser storeUser) {
        List<StoreUser> list = storeMapper.queryStoreUser(storeUser);
        if (list.size()!=0){
            return RespBean.respSuccess("获取店铺信息成功",list);
        }
        return RespBean.respError("获取店铺信息失败");
    }

    @Override
    public RespBean queryStoreUserWolfer(StoreUser storeUser) {

        List<StoreUser> list = storeMapper.queryStoreUserWolfer(storeUser);
        if (list.size()!=0){
            return RespBean.respSuccess("获取店铺信息成功",list);
        }
        return RespBean.respError("获取店铺信息失败");
    }

    @Override
    public RespBean getStoreTotalByUserId(int userId) {
        StoreTotal storeTotal = new StoreTotal();
        Integer produceNumber=0;
        Integer orderNumber=0;
        double price=0;
        List<StoreOrderProduct> list = storeMapper.selectStatistics(userId);
        if (list.size()!=0){
            for (int i = 0; i < list.size(); i++) {
                produceNumber += list.get(i).getNumber();
                price +=list.get(i).getNumber()*list.get(i).getPrice();
            }
            orderNumber=list.size();
            storeTotal.setProduceNumber(produceNumber);
            storeTotal.setOrderNumber(orderNumber);
            storeTotal.setProducePriceTotal(price);
            return RespBean.respSuccess("获取统计信息成功",storeTotal);
        }

        return RespBean.respError("获取统计信息失败");
    }

    public Vo queryAllProduct() {
        List<ProductVo> list = productMapper.queryAllProduct();
        Vo vo = new Vo();
        if (list.size() != 0) {
            vo.setCode(0);
            vo.setMsg("success");
            vo.setCount(list.size());
            vo.setData(list);
            return vo;
        }
        return vo;

    }

    @Override
    public Vo queryProductLimit(HttpServletRequest request,int page, int limit,Integer flag) {
        User user = (User)request.getSession().getAttribute("user");
        Integer uid = user.getId();
        page=(page-1)*limit;
        List<ProductVo> list = productMapper.queryProductLimit(flag,uid,page,limit);
        Integer count = storeMapper.queryProductCount(null, flag, null);
        Vo vo = new Vo();
        if (list.size() != 0) {
            vo.setCode(0);
            vo.setMsg("success");
            vo.setCount(count);
            vo.setData(list);
            return vo;
        }
        return vo;
    }

    @Override
    public Vo queryProductLimitByStoreId(HttpServletRequest request, int page, int limit, Integer flag) {
        Integer storeId = (Integer) request.getSession().getAttribute("storeId");

        page=(page-1)*limit;

        List<ProductVo> list = productMapper.queryProductLimitByStoreId(flag,storeId,page,limit);
        Integer count = storeMapper.queryProductCount(storeId, flag, null);
        Vo vo = new Vo();
        if (list.size() != 0) {
            vo.setCode(0);
            vo.setMsg("success");
            vo.setCount(count);
            vo.setData(list);
            return vo;
        }
        return vo;
    }

    @Override
    public Vo queryProductByTypeId(HttpServletRequest request,int id,int page,int limit,Integer flag) {
        User user = (User)request.getSession().getAttribute("user");
        Integer uid = user.getId();
        page=(page-1)*limit;
        Integer count = storeMapper.queryProductCount(null, flag, id);
        List<ProductVo> list = productMapper.queryProductByTypeId(flag,id,page,limit,uid);
        Vo vo = new Vo();
        if (list.size()!=0){
            vo.setCode(0);
            vo.setMsg("success");
            vo.setCount(count);
            vo.setData(list);
            return vo;
        }
        return vo;
    }

    @Override
    public Vo queryProductByTypeIdAndStoreId(HttpServletRequest request, int id, int page, int limit, Integer flag) {
        Integer storeId = (Integer) request.getSession().getAttribute("storeId");
        page=(page-1)*limit;
        Integer count = storeMapper.queryProductCount(storeId, flag, id);
        List<ProductVo> list = productMapper.queryProductByTypeIdAndStoreId(flag,id,page,limit,storeId);
        Vo vo = new Vo();
        if (list.size()!=0){
            vo.setCode(0);
            vo.setMsg("success");
            vo.setCount(count);
            vo.setData(list);
            return vo;
        }
        return vo;
    }

    @Override
    public RespBean queryProductIdAndName(HttpServletRequest request) {
        Integer storeId = (Integer) request.getSession().getAttribute("storeId");
        List<ProductIdAndName> list = storeMapper.queryProductIdAndNameByStoreId(storeId);
        if (list.size()!=0){
            return RespBean.respSuccess("获取信息成功",list);
        }
        return RespBean.respError("获取信息失败");
    }

    @Override
    public RespBean selectAllStore() {
        List<Store> stores = storeMapper.selectAllStore();
        if (stores.size()!=0){
            return RespBean.respSuccess("获取店铺成功",stores);
        }
        return RespBean.respError("获取店铺失败");
    }

    @Override
    public RespBean getStoreByName(String name) {
        List<Store> store = storeMapper.getStoreByName(name);
        return RespBean.respSuccess("获取店铺成功",store);
    }

    @Override
    public List<Store> queryStoreByFlag(Integer flag) {
        return storeMapper.getStoreByFlag(flag);
    }

    @Override
    public Integer updateStoreFlagById(Integer id) {
        return storeMapper.updateStoreFlag(id);
    }
}
